package com.evan.review.anr;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;

import com.evan.review.R;

/**
 * Service超时ANR示例Activity
 * 演示前台和后台Service执行耗时操作导致的ANR
 */
public class ServiceTimeoutActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "ServiceTimeoutANR";
    private static final String CHANNEL_ID = "anr_service_channel";
    
    private Button btnStartForegroundService; // 启动前台服务按钮
    private Button btnStartBackgroundService; // 启动后台服务按钮
    private TextView tvLogger; // 日志文本框
    private ScrollView svLogger; // 日志滚动视图
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_service_timeout);
        
        initViews(); // 初始化视图
        setListeners(); // 设置监听器
        createNotificationChannel(); // 创建通知渠道
        
        logMessage("提示：点击按钮将启动服务并在服务中执行耗时操作，引发ANR");
        logMessage("服务ANR时间阈值：前台服务20秒、后台服务200秒");
    }
    
    /**
     * 初始化视图组件
     */
    private void initViews() {
        btnStartForegroundService = findViewById(R.id.btn_start_foreground_service);
        btnStartBackgroundService = findViewById(R.id.btn_start_background_service);
        tvLogger = findViewById(R.id.tv_logger);
        svLogger = findViewById(R.id.sv_logger);
    }
    
    /**
     * 设置监听器
     */
    private void setListeners() {
        btnStartForegroundService.setOnClickListener(this);
        btnStartBackgroundService.setOnClickListener(this);
    }
    
    @Override
    public void onClick(View v) {
        int id = v.getId();
        
        if (id == R.id.btn_start_foreground_service) {
            logMessage("启动前台服务...");
            Intent intent = new Intent(this, ANRForegroundService.class);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(intent);
            } else {
                startService(intent);
            }
        } else if (id == R.id.btn_start_background_service) {
            logMessage("启动后台服务...");
            Intent intent = new Intent(this, ANRBackgroundService.class);
            startService(intent);
        }
    }
    
    /**
     * 创建通知渠道（Android 8.0及以上版本需要）
     */
    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String name = "ANR Service Channel";
            String description = "Channel for ANR service demonstration";
            int importance = NotificationManager.IMPORTANCE_LOW;
            
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
            channel.setDescription(description);
            
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            if (notificationManager != null) {
                notificationManager.createNotificationChannel(channel);
            }
        }
    }
    
    /**
     * 记录日志信息到界面
     */
    private void logMessage(String message) {
        Log.d(TAG, message);
        
        runOnUiThread(() -> {
            String currentText = tvLogger.getText().toString();
            String newText = currentText + "\n" + message;
            tvLogger.setText(newText);
            
            // 滚动到底部
            svLogger.post(() -> svLogger.fullScroll(View.FOCUS_DOWN));
        });
    }
    
    /**
     * 前台服务实现
     * 在onStartCommand中执行耗时操作超过20秒，触发ANR
     */
    public static class ANRForegroundService extends Service {
        private static final String TAG = "ANRForegroundService";
        private static final int NOTIFICATION_ID = 1;
        
        @Override
        public void onCreate() {
            super.onCreate();
            Log.d(TAG, "前台服务已创建");
            
            // 创建前台服务通知
            Notification notification = createNotification();
            startForeground(NOTIFICATION_ID, notification);
        }
        
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            Log.d(TAG, "前台服务已启动，将执行耗时操作...");
            
            // 执行耗时操作，超过20秒将导致ANR
            // 前台服务ANR阈值为20秒
            Log.d(TAG, "前台服务开始执行耗时操作，将持续30秒...");
            SystemClock.sleep(30000); // 睡眠30秒，确保超过ANR阈值
            Log.d(TAG, "前台服务耗时操作完成（如果看到此日志，说明ANR未被处理）");
            
            stopSelf();
            return START_NOT_STICKY;
        }
        
        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
        
        @Override
        public void onDestroy() {
            super.onDestroy();
            Log.d(TAG, "前台服务已销毁");
        }
        
        /**
         * 创建前台服务通知
         */
        private Notification createNotification() {
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
                    .setSmallIcon(android.R.drawable.ic_dialog_alert)
                    .setContentTitle("ANR前台服务示例")
                    .setContentText("正在执行可能导致ANR的耗时操作...")
                    .setPriority(NotificationCompat.PRIORITY_LOW);
            
            return builder.build();
        }
    }
    
    /**
     * 后台服务实现
     * 在onStartCommand中执行耗时操作超过200秒，触发ANR
     */
    public static class ANRBackgroundService extends Service {
        private static final String TAG = "ANRBackgroundService";
        
        @Override
        public void onCreate() {
            super.onCreate();
            Log.d(TAG, "后台服务已创建");
        }
        
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            Log.d(TAG, "后台服务已启动，将执行耗时操作...");
            
            // 执行耗时操作，超过200秒将导致ANR
            // 后台服务ANR阈值为200秒
            Log.d(TAG, "后台服务开始执行耗时操作...");
            Log.d(TAG, "注意：后台服务ANR阈值为200秒，实际操作将模拟30秒耗时");
            Log.d(TAG, "在生产环境中，应避免在Service.onStartCommand()中执行任何耗时操作");
            
            // 为了演示，这里只睡眠30秒，实际ANR阈值是200秒
            SystemClock.sleep(30000);
            Log.d(TAG, "后台服务耗时操作完成");
            
            stopSelf();
            return START_NOT_STICKY;
        }
        
        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
        
        @Override
        public void onDestroy() {
            super.onDestroy();
            Log.d(TAG, "后台服务已销毁");
        }
    }
} 